//
//  LYKeyBoardView.m
//  6park
//
//  Created by TI on 15/5/5.
//  Copyright (c) 2015年 6park. All rights reserved.
//

#import "LYKeyBoardView.h"
#import "KeyBoardAnimationV.h"
#import "UIColor+Extension.h"

#define   i_lf    12.0f
#define   i_top   8.0f
#define   i_w_h   28.0f
#define   Fit_Num 10.0f

#define   W_D     ([UIScreen mainScreen].bounds.size.width)
@interface LYKeyBoardView()<UITextViewDelegate>
{
    NSArray * icons;
    CGFloat hight_text_one;
    CGFloat end_text_hight;
    
    BOOL  keyBoardTap;

}

//@property (nonatomic,strong)UIButton * audio;
//@property (nonatomic,strong)UIButton * emoji;
@property (nonatomic,strong)UIButton * sendButton;

@property (nonatomic,strong)KeyBoardAnimationV * bottomView;
@end

@implementation LYKeyBoardView

#pragma mark - init 初始化
-(instancetype)initDelegate:(id)delegate superView:(UIView *)superView{
    if (self = [super init]) {
        [self initUI];
        [self addNotifations];
        [self addToSuperView:superView];
        self.delegate = delegate;
    }
    return self;
}

-(void)initUI{
    [self addTopAndBot];
    [self addTextView];
    [self addSendButton];
}

-(void)addTopAndBot{
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(-1, 0, W_D + 2, 44)];
    self.topView.backgroundColor = [UIColor whiteColor];
    self.topView.layer.borderWidth = 0.7f;
    self.topView.layer.borderColor = [UIColor Grey].CGColor;
    [self addSubview:self.topView];
    
    self.bottomView = [[KeyBoardAnimationV alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.topView.frame), W_D, 210)];
    self.bottomView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.bottomView];
}

-(void)addTextView{
    self.inputText = [[UITextView alloc]init];
    _inputText.layer.cornerRadius = 5.0f;
    _inputText.font = [UIFont systemFontOfSize:15.0f];
    _inputText.layer.borderColor = [UIColor Grey].CGColor;
    _inputText.layer.borderWidth = 0.7f;
    _inputText.backgroundColor = [UIColor LightSmoke];
    _inputText.delegate = self;
    _inputText.returnKeyType = UIReturnKeyNext;
    _inputText.enablesReturnKeyAutomatically = YES;
    _inputText.textContainerInset = UIEdgeInsetsMake(5, 0, 5, 0);
    hight_text_one = [_inputText.layoutManager usedRectForTextContainer:_inputText.textContainer].size.height;
    _inputText.frame = CGRectMake(i_lf, i_top, W_D-60, hight_text_one+Fit_Num);
    [self.topView addSubview:self.inputText];
}

- (void)addSendButton {
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sendButton setFrame:CGRectMake(CGRectGetMaxX(_inputText.frame), CGRectGetHeight(self.topView.frame)-40, 40, 40)];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sendButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.sendButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [self.topView addSubview:self.sendButton];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.sendButton setFrame:CGRectMake(CGRectGetMaxX(_inputText.frame), CGRectGetHeight(self.topView.frame)-40, 40, 40)];
}

-(void)addNotifations{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHiden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
}

-(void)addToSuperView:(UIView *)superView{
    CGFloat s_h = CGRectGetHeight(superView.bounds);
    CGRect frame = CGRectMake(0,s_h,W_D, s_h);
    self.frame = frame;
    [superView addSubview:self];
}

#pragma mark - 系统键盘通知事件
-(void)keyBoardHiden:(NSNotification*)noti{
    if (keyBoardTap==NO) {
        CGRect endF = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
        CGFloat duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGRect fram = self.frame;
//        fram.origin.y = (endF.origin.y - _topView.frame.size.height);
        fram.origin.y = endF.origin.y;
        [self duration:duration EndF:fram];
    }else{
        keyBoardTap = NO;
    }
}

-(void)keyBoardShow:(NSNotification*)noti{
    CGRect endF = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    if (keyBoardTap==NO) {
        for (UIButton * b in icons) {
            b.selected = NO;
        }
        [self.bottomView addSubview:[UIView new]];
        
        NSTimeInterval duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGRect fram = self.frame;
        fram.origin.y = (endF.origin.y - _topView.frame.size.height);
        [self duration:duration EndF:fram];
    }else{
        keyBoardTap = NO;
    }
}

#pragma mark - text View Delegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if(![textView hasText] && [text isEqualToString:@""]) {
        return NO;
    }
//    if ([text isEqualToString:@"\n"]) {
//        [self sendMessage];
//        return NO;
//    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    [self textViewChangeText];
}
#pragma mark - other logic
-(void)topLayoutSubViewWithH:(CGFloat)hight{
    CGRect frame = self.topView.frame;
    CGFloat diff = hight - frame.size.height;
    frame.size.height = hight;
    self.topView.frame = frame;
    
    frame = self.bottomView.frame;
    frame.origin.y = CGRectGetHeight(self.topView.bounds);
    self.bottomView.frame = frame;
    
    frame = self.frame;
    frame.origin.y -= diff;
    
    [self duration:DURTAION EndF:frame];
}

-(void)duration:(CGFloat)duration EndF:(CGRect)endF{
    [UIView animateWithDuration:duration animations:^{
        keyBoardTap = NO;
        self.frame = endF;
    }];
}

-(void)sendMessage{
    if (![self.inputText hasText]&&(self.inputText.text.length==0)) {
        return;
    }
    NSString *plainText = self.inputText.text;
    //空格处理
    plainText = [plainText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (plainText.length > 0) {
        [self sendMessage:plainText];
        self.inputText.text = @"";
        [self textViewChangeText];
    }
}

#pragma mark - self public api action

-(void)textViewChangeText{
    CGFloat h = [self.inputText.layoutManager usedRectForTextContainer:self.inputText.textContainer].size.height;
    self.inputText.contentSize = CGSizeMake(self.inputText.contentSize.width, h+Fit_Num);
    CGFloat five_h = hight_text_one*5.0f;
    h = h>five_h?five_h:h;
    CGRect frame = self.inputText.frame;
    CGFloat diff = self.topView.frame.size.height - self.inputText.frame.size.height;
    
    if (frame.size.height == h+Fit_Num) {
        CGPoint cursorPosition = [self.inputText caretRectForPosition:self.inputText.selectedTextRange.start].origin;
        if ((h == five_h) && (cursorPosition.y > five_h)) {
            CGFloat offsitY = cursorPosition.y < (self.inputText.contentSize.height - h/5.0f)?(cursorPosition.y - h/2.5):(self.inputText.contentSize.height - (h + Fit_Num));
            [self.inputText setContentOffset:CGPointMake(0, offsitY) animated:NO];
        }
        return;
    }
    
    frame.size.height = h+Fit_Num;
    self.inputText.frame = frame;
    [self topLayoutSubViewWithH:(frame.size.height+diff)];
    [self.inputText setContentOffset:CGPointZero animated:YES];
}

#pragma mark - self delegate action

-(void)sendMessage:(NSString*)message{
    if ([self.delegate respondsToSelector:@selector(keyBoardView:sendMessage:)]) {
        [self.delegate keyBoardView:self sendMessage:message];
        [self.inputText resignFirstResponder];
    }
}

- (void)sendButtonAction:(UIButton *)sender {
    
    [self sendMessage];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
